//公共参数

var URL = {
    // 'action': 1, //正式
    // 'serverUrl': 'http://hghq.cpp.gg/server/',
    'action': 0, //测试
    // 'action': 2, //本地模拟
    // 'website': 'http://a.t.yuzijiang.tv:63000/',
    // 'website': 'https://test.yuzijiang.tv/',

    official: {
        // 'me': 'server/'
        'me': 'http://hghq.cpp.gg/server/',
        'img': 'http://hghq.cpp.gg/'
    },
    test: {
        'me': 'http://127.0.0.1:8085/',
        'img': 'image/'
    },
    simulation: {
        'me': 'test/',
        'img': 'image/'
    }
};

var OBJ_BAG = {
    weixin_appid: 'wxb08b9e29bb57f0d8',
    // qq_appid: '101358937',
    // weibo_appid: '1569382990',
    // pay_weixin_appid: 'wxb08b9e29bb57f0d8',
    login_type: {
        type: 'baic'
    },
    download: {
    },
    local_prefix: 'rtw_' + URL.action,
    // local_prefix: 'rtw_' + '1',
    folder_pre: '0001'
};

//服务器基本地址
// var SERVER_URL = 'http://a.t.yuzijiang.tv:63000/'

//第三方登录验证页面
var reUrl = getUrl() + 'verify_login.html';

/**
 * 关闭H5窗口
 * 
 */
function addBackBtn() {
    if (Common.Browser.Versions().ios) {
        var html = '<header class="header-gohistory">返回上一级</header>';

        $(html).prependTo('body').on('click', function () {
            window.history.go(-1);
        });
    }
}

/**
 * 判断后退时重新加载页面
 */
function backReload() {
    var isPageHide = false;

    $(window).on('pageshow', function () {
        if (isPageHide) {
            window.location.reload();
        }
    }).on('pagehide', function () {
        isPageHide = true;
    });
}

(function () {
    // setGuidAgentInfoID();

    // addBackBtn();

    // backReload();
})();

/**
 * 返回主网址
 * 
 * @returns 网址
 */
function getUrl() {
    var href = window.location.href;
    var index = href.lastIndexOf('/') + 1;

    href = href.substring(0, index);

    return href;
}

//生成调用服务器地址
// function createServerUrl(service, method) {
//     var len = arguments.length;
//     var result = '';

//     if (len === 1) {
//         URL.temp = SERVER_URL;
//         method = service;
//         service = 'temp';
//     }

//     var serviceUrl = URL[service.replace(/ /g, '')];
//     method = method && method.replace(/ /g, '');

//     if (URL.action) {
//         serviceUrl = serviceUrl.replace('t.', '');

//         var index = 4;
//         var httpId = serviceUrl.substring(0, index);

//         var urlArr = serviceUrl.substring(index + 3).split(':')[0].split('.');
//         var headerId = urlArr.shift();

//         serviceUrl = httpId + '://s.' + urlArr.join('.') + '/' + headerId + '/';
//     }

//     result = serviceUrl + method;

//     return result;
// }
function createServerUrl(method, serverUrl) {
    var result = '';
    serverUrl = serverUrl ? serverUrl : 'me';

    if (URL.action === 0) {
        method = method ? method.replace(/ /g, '') : '';

        var serviceUrl = URL.test[serverUrl];

        result = serviceUrl + method;

    } else if (URL.action === 1) {
        method = method ? method.replace(/ /g, '') : '';

        var serviceUrl = URL.official[serverUrl];

        result = serviceUrl + method;
    } else if (URL.action === 2) {
        method = method ? method.replace(/ /g, '') : '';

        result = URL.simulation[serverUrl] + method.replace(/\//g, '.') + '.json';
    }

    return result;
}
function createImgUrl(imgName) {
    var result = '';
    var serviceUrl = '';
    var urlName = 'img';

    imgName = imgName ? imgName.replace(/ /g, '') : '';

    if (URL.action === 0) {
        serviceUrl = URL.test[urlName];
    } else if (URL.action === 1) {
        serviceUrl = URL.official[urlName];
    } else if (URL.action === 2) {
        serviceUrl = URL.official[urlName];
    }

    result = serviceUrl + imgName;

    return result;
}

/**
 * 判断是否在app中打开
 */
function isApp() {
    var result = 0;

    var params = getUrlParamsToJson();
    var appKey = 'app_user'
    var userObj = saveJsonData().getData(appKey, 1);
    if (params.t === 'app' || userObj) {
        result = 1;
    }

    return result;
}

//返回结果是否成功
function getResult(result) {
    return !result;
}
/*
 * no:01
 * 调用手机端的方法
 * author:陈偲
 * time:20160905
 */
function callPhotoFunc(androidFunc, iosFunc) {
    var result;
    var browser = Common.Browser.Versions();

    if (browser.android) {
        result = androidFunc && androidFunc();
    } else if (browser.iPhone || browser.iPad) {
        result = iosFunc && iosFunc();
    }

    return result;
}

/*
 * no:13
 * 调用pc和手机端的方法
 * author:陈偲
 * time:20170122
 */
function pcAndPhoneFunc(pcFunc, phoneFunc) {
    var result;
    var browser = Common.Browser.Versions();

    if (browser.win) {
        result = pcFunc && pcFunc();
    } else {
        result = phoneFunc && phoneFunc();
    }

    return result;
}

/*
 * no:02
 * px转rem
 * author:陈偲
 * time:20160930
 */
function pxToRem(pxVal) {
    var fontSizeBase = Number($('html').css('font-size').replace('px', ''));

    return (pxVal / fontSizeBase).toFixed(2).toString() + 'rem';
}
/*
 * no:03
 * 是否是微信浏览器
 * author:陈偲
 * time:20160930
 */
function isWeixinBrowser(func) {
    var $obj = $(".share");

    if (Common.Browser.Versions().weixin) {
        $obj.hide();
    } else {
        $obj.show();

        func && func();
    }
}
/*
 * no:04
 * 确认弹出框的处理
 * author:陈偲
 * time:20161026
 */
function confirmProgram(options, cancelFunc, certainFunc) {
    var $obj = $(".confirm-info,.layout");
    var $dialogObj;
    if ($obj.length) {
        $dialogObj = $obj.filter('.confirm-info');
    } else {
        $obj = $(options.ids);
        $dialogObj = $obj.filter(options.ids.split(',')[0].toString());
    }

    var defaults = $.extend({
        contentTxt: null, //显示内容
        cancelTxt: '',
        certainTxt: '',
    }, options);

    var settings = $.extend({}, defaults, options);

    $obj.show();
    $dialogObj.find('.content').html(settings.contentTxt);
    $dialogObj.find('.cancel').children().one('click', function () {
        cancelFunc && cancelFunc();

        $dialogObj.find('.choose-info *').unbind();
        $obj.hide();
    }).text(settings.cancelTxt);
    $dialogObj.find('.comfirm').children().one('click', function () {
        certainFunc && certainFunc();

        $dialogObj.find('.choose-info *').unbind();
        $obj.hide();
    }).text(settings.certainTxt);

    if (!settings.certainTxt) {
        $dialogObj.find('.comfirm').hide();
        $dialogObj.find('.cancel').children().css('width', '100%');
    }
}

/*
 * no:05
 * 当hash变化时执行函数
 * author:陈偲
 * time:20161026
 */
function hashChangeFunc(func, obj, complateFunc) {
    function hanlderFunc(tempFunc, o) {
        var hash = window.location.hash.substring(1);
        var hashArr = hash.split('#');
        if (hashArr.length === 1) {
            hashArr = hash.split('?');
        }
        var paramJson = $.extend(true, o, getParamToJson(hashArr[1]));

        tempFunc && tempFunc(hashArr[0], paramJson, complateFunc);
    }

    hanlderFunc(func, obj);

    $(window).on('hashchange', function () {
        hanlderFunc(func, obj);
    });
}

/**
 * no:07
 * 更换token
 * author:陈偲
 * time:20161110
 * @param {any} token   token
 * @param {any} func    回调
 * @returns
 */
function validLogin(token, func) {
    var url = createServerUrl('baiyunpeng', 'user/valid');
    Common.AjaxPostData(url, {
        'token': token
    }, function (ret) {
        func(ret);
    });
}

/**
 * no:08
 * 设置图片大小
 * author:陈偲
 * time:20161201
 * @param {any} imgObj    图片实体
 * @param {any} displayWidth    显示宽
 * @param {any} displayHeight    显示高
 */
function setImg(imgObj, displayWidth, displayHeight) {
    var width = imgObj.width;
    var height = imgObj.height;

    imgObj.style.left = 0;
    imgObj.style.top = 0;
    imgObj.style.position = 'absolute';

    var needRatio = displayWidth / displayHeight;

    var ratio = width / height / needRatio; //图片宽高比比

    if (ratio < 1) { //宽按比例小于高
        imgObj.style.width = '100%';

        imgObj.style.top = pxToRem(-Math.abs(height + height * ((displayWidth - width) / width) - displayHeight) / 2);
        // imgObj.style.top = -Math.abs(height + height * ((displayWidth - width) / width) - displayHeight) / 2 + 'px';
    } else if (ratio == 1) { //宽按比例等于高
        imgObj.style.width = '100%';
    } else if (ratio > 1) { //宽按比例大于高
        imgObj.style.height = '100%';

        imgObj.style.left = pxToRem(-Math.abs(width + width * ((displayHeight - height) / height) - displayWidth) / 2);
        // imgObj.style.left = -Math.abs(width + width * ((displayHeight - height) / height) - displayWidth) / 2 + 'px';
    }

    return imgObj;
}

/**
 * no:10
 * 设置头像
 * author:陈偲
 * time:20161216
 */
function setHeader() {
    var $obj = $('.go-user');

    if ($obj.length) {
        var data = saveJsonData().getData('user_info', 1);

        if (data) {
            var imgObj = new Image();
            imgObj.src = data.photo;
            imgObj.onload = function () {
                $obj.find('a').html(imgObj);
            }
        }
    }
}
/**
 * no:11
 * 兑换按钮的点击
 * author:陈偲
 * time:20161227
 * 
 * @param {object} paramObj 参数
 */
function exchangeClick(paramObj) {
    var tempObj = {
        url: '',
        $thatObj: $(),
        totalLeft: 0,
        token: '',
        // confirmId: '',
        completeFunc: $.noop()
    };

    var obj = $.extend(true, tempObj, paramObj);

    var displayText = '';

    if (obj.url.indexOf('coin2Coin') > -1) {
        displayText = '恭喜获得' + obj.$thatObj.attr('data-gain') + '钻石';
        obj.successId = '.confirm4-info-20170101';
        obj.confirmId = '.confirm5-info-20170101';
    } else if (obj.url.indexOf('star2Yuzi') > -1) {
        displayText = '恭喜获得' + obj.$thatObj.attr('data-gain') + '鱼子';
        obj.successId = '.confirm2-info-20170101';
        obj.confirmId = '.confirm3-info-20170101';
    }

    if (obj.$thatObj.length) {
        if (Number(obj.$thatObj.attr('data-expend')) <= obj.totalLeft) {
            var data = {
                // token: '119cf66c3d6c5f369b2bf9638105c51b',
                token: obj.token,
                exchangeId: obj.$thatObj.attr('data-id'),
                count: 1
            };
            // var url = createServerUrl('biling', 'activity/star2Yuzi');

            Common.AjaxPostData(obj.url, data, function (r) {
                if (getResult(r.code)) {
                    var result = r.msg;

                    var $alertObj = $('.layout-activity,' + obj.successId);
                    $alertObj.find('.info').text(displayText).end().find('.text-info').show().end().show().find('.cancel').children().one('click', function () {
                        $alertObj.find('.text-info').hide().end().hide();
                    });
                } else {
                    Common.toast(JSON.stringify(r.info), 5000);
                }

                obj.completeFunc && obj.completeFunc();
            });
        } else {
            var $alertObj = $('.layout-activity,' + obj.confirmId);
            $alertObj.show().find('.cancel').children().one('click', function () {
                $alertObj.hide();
                obj.completeFunc && obj.completeFunc();
            });
        }
    } else {
        var $alertObj = $('.layout-activity,.confirm1-info-20170101');
        $alertObj.show().find('.cancel').children().one('click', function () {
            $alertObj.hide();
            obj.completeFunc && obj.completeFunc();
        });
    }
}

/**
 * no:12
 * 获取客户端反馈给我的内容,对外暴露的客户端信息反馈接口
 * author:陈偲
 * time:20170526
 * 
 * @param {any} result 
 * @param {any} type 1.投票扣除金币
 */
function getInfo(result, type) {
    // $('body').prepend('<div>1.' + JSON.stringify(result) + '</div>');
    // Common.toast(type, 10000);

    type = Math.abs(type || 1);

    if (type == 1) {
        result = typeof (result) == 'object' ? result.result.result : result;

        // Common.toast('1.' + result, 10000);
        // $('body').prepend('<div>1.' + JSON.stringify(result) + '</div>');

        if (result == 0) {
            window.SuccessVote();
        } else if (result == 603) {
            Common.toast('您的余额已不足，请先充值', 3000);
            window.FailVote();
        }
    } else {
        Common.toast('未知的type:' + type, 10000);
    }
}

/**
 * no:16
 * 电影相关图片
 * author:陈偲
 * time:20170413
 * 
 * @param {any} obj 
 * @param {any} movieDir 
 * @returns 
 */
function loadMovieImg(obj, movieDir, roleIdArr) {
    var picMoviePath = OBJ_BAG.pic.pic_path + movieDir + '/';
    // var picMoviePath = 'img/';

    var picHeaderPath = picMoviePath + OBJ_BAG.pic.role.header + movieDir + '/';

    for (var key in OBJ_BAG.pic.movie) {
        var item = OBJ_BAG.pic.movie[key];

        obj[key] = picMoviePath + item;
    }

    for (var key in obj) {
        var item = obj[key];

        if (item.indexOf('@') < 0) {
            obj[key] += OBJ_BAG.pic.style.art;
        }
    }

    saveJsonData().setData('imgs', obj, 1);

    return obj;
}

/**
 * no:16
 * 电影角色头像
 * author:陈偲
 * time:20170716
 * 
 * @param {any} obj 
 * @param {any} movieDir 
 * @returns 
 */
function loadMovieHeaderImg(obj, movieDir, roleId) {
    var picMoviePath = OBJ_BAG.pic.pic_path + movieDir + '/';
    // var picMoviePath = 'img/';

    var picHeaderPath = picMoviePath + OBJ_BAG.pic.role.header + '/' + roleId + OBJ_BAG.pic.role.ext;

    obj.header = picHeaderPath;

    return obj;
}

/**
 * no:16
 * url跳转函数
 * author:陈偲
 * time:20170629
 * 
 * @param {String} url 
 */
function urlSkip(url) {
    var type = saveJsonData().getData('type', 0);
    var prefix = '&';

    if (type == 3) {
        var jsbridge = 'jsbridge://ui/openUrl';
        var postfix = '_wv=16778245';
        var index = url.indexOf(postfix);

        if (index === -1) {
            var urlArr = url.split('#');

            if (urlArr[0].indexOf('?') === -1) {
                prefix = '?';
            }

            urlArr[0] += (prefix + postfix);

            url = urlArr.join('#');
        }

        var params = {
            url: Common.getWebsiteOfDomainAndPath() + url,
            target: 1
        };

        callProtoFunc.callProto(jsbridge, params);
    } else {
        var m = getUrlParamsToJson().m;

        if (m) {
            if (url.indexOf('?') != -1) {
                prifix = '?';
            }

            url += (prifix + 'm' + m);
        }

        window.location = url;
    }
}

/**
 * 加载分布页
 * author:陈偲
 * time:20170401
 * 
 * @param {any} pageName 
 * @param {any} prevFunc 
 * @param {any} laterFunc 
 * */
function getPage(pageName, prevFunc, laterFunc, isAppend) {
    // Common.preloader.show();

    // var $content = $('#getPage');

    // $.get(pageName + '.html', function (r) {
    //     var html = prevFunc ? prevFunc(r) : r;

    //     // $('#content_info').html('').html(html);

    //     $('#main_container').html('').html(html);

    //     laterFunc && laterFunc(html);

    //     Common.preloader.hide();
    // });

    Common.preloader.show();

    $.get(pageName + '.html?_t=' + (new Date().getTime()), function (r) {
        var html = prevFunc ? prevFunc(r) : r;

        $('#main_container').empty().html(html);

        laterFunc && laterFunc(html);

        Common.preloader.hide();
    });
}

/**
 * 上传文件
 * 
 * @param {any} file 
 */

/**
 * 上传控件
 * author:陈偲
 * time:20170805
 */
function uploadControl($id, func) {
    var $input = $($id);
    var result = $("#result");

    $(function () {

        //var img_area = document.getElementById("img_area");
        if (typeof (FileReader) === 'undefined') {
            result.html("不支持的文件");
            $input.attr('disabled', true);
        } else {
            $input.on('change', readFile);
        }
    });

    function readFile() {
        var file = this.files[0];

        var $cloneInput = $input.clone();
        $input.replaceWith($cloneInput);

        $cloneInput.on('change', readFile);

        if (!file) {
            return;
        }

        if (!/image\/\w+/.test(file.type)) {
            alert("只支持上传图片");
            return false;
        }

        /**
         * 上传头像
         */
        var bucket = 'yzj/web/marketing-img';

        var reader = new FileReader();
        reader.readAsDataURL(file);

        reader.onload = function () {
            var serverFilename = CryptoJS.MD5(reader.result).toString();

            var filename = file.name;
            var ext = filename.substring(filename.lastIndexOf('.'), filename.length); //取得文件的后缀名

            serverFilename += ext;

            Common.preloader.show();
            Ks3.putObject({
                Bucket: bucket,
                region: 'BEIJING',
                Key: serverFilename,
                File: file,
                ACL: 'public-read',
                Sinature: ''
            }, function (err) {
                var url = 'https://image.yuzijiang.tv/web/marketing-img/' + serverFilename;
                var result = {
                    code: err ? 1 : 0,
                    err: err,
                    controlObj: $($id),
                    msg: url
                };

                func && func(result);
                Common.preloader.hide();
            });
        }
    }
}

// function uploadFile(file, ) {
//     var objKey = Ks3.encodeKey(file.name);
//     var contentType = file.type;
//     var bucket = 'yzj/web/marketing-img';

//     Ks3.putObject({
//         Bucket: bucket,
//         // region: 'BEIJING',
//         Key: objKey,
//         File: file,
//         ACL: 'public-read',
//         ProgressListener: progressFunction,
//         Sinature: ''
//     }, function (err) {
//         if (err) {
//             console.log(err);
//         } else {
//             func && func(fileName)
//         }
//     });

//     function progressFunction(e) {
//         var progressBar = document.getElementById("progressBar2");
//         if (e.lengthComputable) {
//             progressBar.max = e.total;
//             progressBar.value = e.loaded;
//         }
//     }
// }

/**
 * no:11
 * 分享按钮的点击
 * author:陈偲
 * time:20170605
 * 
 * @param {any} user 
 * @param {any} anchor 
 */
function shareFunc(url, title, img, des) {
    var type = saveJsonData().getData('type', 0);
    var isShare = !!saveJsonData().getData('user', 1);

    var shareClickFunc = function () {
        var type = saveJsonData().getData('type', 0);

        if (isShare) {
            var shareType;
            var nowAppParams = [];

            if (Common.Browser.Versions().ios) {
                shareType = 'mqq/app/doShare';

                nowAppParams.push('type=' + 2);
                nowAppParams.push('image=' + img);
                nowAppParams.push('title=' + title);
                nowAppParams.push('desc=' + des);
            } else {
                shareType = 'ui/openSharePage';

                nowAppParams.push('source=5');
                nowAppParams.push('bNewQZone=true');
                nowAppParams.push('desc=' + des);
                nowAppParams.push('title=' + title);
                nowAppParams.push('imageUrl=' + img);
                nowAppParams.push('anchorUin=0');
                nowAppParams.push('roomId=0');
            }

            /**
             * 当时非ios机器的时候的调用函数
             */
            var misIosFunc = function () {
                if (!Common.Browser.Versions().ios) {
                    var data = {
                        default: {
                            anchorUin: 0,
                            bNewQZone: true,
                            desc: des,
                            imageUrl: img,
                            roomId: 0,
                            source: 5,
                            title: title,
                            url: encodeURIComponent(url)
                        }
                    };

                    nowAppParams.push('data=' + JSON.stringify(data));
                }
            };

            if (type == 1) {
                url += '&m=yzj';
                callPhotoFunc(function () {
                    window.android.share(
                        url, title, des, img
                    );
                }, function () {
                    var param = {
                        'method': 'share',
                        'args': [url, title, des, img].join(',')
                    };
                    window.webkit.messageHandlers.Caviar.postMessage(param);

                });
            } else if (type == 2) {
                if (Common.Browser.Versions().ios) {
                    $('#share_layer,.modal-overlay').show();

                    OBJ_BAG.shareForYuzijiangIOS = {
                        des: des,
                        title: title,
                        img: img,
                        url: url
                    };
                } else {
                    url += '&m=yzj'
                    nowAppParams.push('url=' + encodeURIComponent(url));

                    misIosFunc();

                    shareType += ('?' + nowAppParams.join('&'));

                    $('<iframe style="display:none;">').appendTo('body').attr('src', 'jsbridge://' + shareType);
                }
            } else if (type == 3) {
                url += '&m=now'

                if (Common.Browser.Versions().ios) {
                    shareType = 'ui/openShare';

                    $('<iframe style="display:none;">').appendTo('body').attr('src', 'jsbridge://' + shareType);

                    if (!window.execEventCallback) {
                        window.execEventCallback = function (infoStr, data) {
                            /**
                             * 如果是分享
                             */
                            if (infoStr === 'onGetShareInfo') {
                                shareType = 'ui/onShareInfo';

                                nowAppParams = [];

                                nowAppParams.push('type=' + JSON.parse(data.data.type));
                                nowAppParams.push('bNewQZone=0');
                                nowAppParams.push('imageUrl=' + img);
                                nowAppParams.push('title=' + title);
                                nowAppParams.push('desc=' + des);
                                nowAppParams.push('url=' + encodeURIComponent(url));

                                shareType += ('?' + nowAppParams.join('&'));

                                $('<iframe style="display:none;">').appendTo('body').attr('src', 'jsbridge://' + shareType);
                            }
                        };
                    }
                } else {
                    nowAppParams.push('url=' + encodeURIComponent(url));

                    misIosFunc();

                    shareType += ('?' + nowAppParams.join('&'));

                    $('<iframe style="display:none;" id="ifrm_share">').appendTo('body').attr('src', 'jsbridge://' + shareType);

                    // callProto('jsbridge://mqq/app/doShare', paramObj);
                }
            } else if (type == 4) {

            } else if (type == 5) {

            }
        } else {
            if (type == 4) {
                url += '&m=yzj'
            } else if (type == 5) {
                url += '&m=now'
            }

            if (Common.Browser.Versions().weixin) {
                $('.share-tip-layer').show();
            } else {
                Common.toast('暂时只支持微信分享', 5000);
            }
        }

        setTimeout(function () {
            $('.share').one('click', shareClickFunc);
        }, 30);
    };

    $('.share').one('click', shareClickFunc);

    if (type == 2 && Common.Browser.Versions().ios) {
        shareLayer();
    }
}

function shareLayerForWeixin() {
    $('.share-tip-layer').on('click', function () {
        $(this).hide();
    })
}

//把json数据转化成get的参数形式 
function jsonToGetParam(json) {
    //对json字符串进行排序以生成sign
    function JsonSort(json) {
        var result = {};
        var arrSort = [];

        for (var key in json) {
            arrSort.push([key.toLowerCase(), json[key]]);
        }

        arrSort.sort(function (a, b) {
            return a[0] > b[0] ? 1 : -1;
        });

        for (var i = 0; i < arrSort.length; i++) {
            var item = arrSort[i];

            result[item[0]] = item[1];
        }

        return result;
    }

    var result = '';

    json = JsonSort(json);

    if (json) {
        for (var key in json) {
            if (result) {
                result = result + '&' + key + '=' + json[key];
            } else {
                result = key + '=' + json[key];
            }
        }
    }

    return result;
}
//把get参数形式的字符串转化成json
function getParamToJson(gStr) {
    var result = gStr;

    if (result) {
        var paramsArr = result.replace('#', '&').split('&');

        for (var i = 0; i < paramsArr.length; i++) {
            var item = paramsArr[i].split('=');

            if (!i) {
                result = '"' + item[0] + '"' + ':' + '"' + item[1] + '"';
            } else {
                result += ',' + '"' + item[0] + '"' + ':' + '"' + item[1] + '"';
            }
        }

        // result = result.replace(/_/g, '-')
        result = '{' + result + '}';

        result = JSON.parse(result);

        var tempJson = {
            'gaid': '',
            'nav1': '',
            'nav2': ''
        }

        result = $.extend(tempJson, result);
    } else {
        result = {};
    }

    return result;
}

function setJsonToParam(json) {
    window.location.hash = jsonToGetParam(json);
}

//保存数据(永久)
//author:陈偲
//time:20161207
function saveJsonData() {
    return {
        setData: function (key, data, type) {
            type = type == 0 ? 0 : 1;

            if (type) {
                data = JSON.stringify(data);
            }

            localStorage.setItem(OBJ_BAG.local_prefix + key, data);
        },
        getData: function (key, type) {
            type = type == 0 ? 0 : 1;

            var result = localStorage.getItem(OBJ_BAG.local_prefix + key);

            if (type) {
                result = JSON.parse(result);
            }

            return result;
        },
        isExists: function (key) {
            return !!(localStorage.getItem(OBJ_BAG.local_prefix + key));
        },
        /*
         * no:06
         * 清理指定的localStorage
         * author:陈偲
         * time:20161105
         */
        clearAppointLocalStorage: function (nameArr) {
            if (nameArr) {
                for (var i = 0; i < nameArr.length; i++) {
                    var item = nameArr[i];

                    localStorage.removeItem(OBJ_BAG.local_prefix + item);
                }
            }
        }
    }
}

//从URL中提取参数以JSON形式返回
function getUrlParamsToJson() {
    var result = {};
    var hash = window.location.hash;

    if (hash) {
        // hash = hash.substring(1);
        hash = hash.split('?')[1] || hash.split('#')[1];
        if (hash) {
            hash = decodeURIComponent(hash)
            result = getParamToJson(hash);
        }
    }

    var search = window.location.search;

    if (search) {
        result = $.extend(result, getParamToJson(search.substring(1)));
    }

    return result;
}

/*
 * 取得登录标识
 */
function setGuidAgentInfoID() {
    var result = '';
    var type = getGuidAgentInfoID();

    if (type == 1) {
        result = 1; //鱼子酱原生app进入
    } else if (type == 2 || type == 1007) {
        result = 2; //鱼子酱sdk进入
    } else if (type == 'yzj') {
        result = 4; //鱼子酱分享
    } else if (type == 'now') {
        result = 5; //now分享
    } else {
        result = 3; //nowapp进入
    }

    saveJsonData().setData('type', result, 0);
}

/*
 * 获取登录标识
 */
function getGuidAgentInfoID() {
    var paramsObj = getUrlParamsToJson();

    // $('<div>').prependTo('body').html('href:' + window.location.href);
    // $('<div>').prependTo('body').html('window.history.length:' + window.history.length);

    if (window.history.length === 1) {
        saveJsonData().clearAppointLocalStorage(['type']);
    }

    var result = paramsObj.appid || paramsObj.type || paramsObj.m || saveJsonData().getData('type', 0);

    // $('<div>').prependTo('body').html('type:' + paramsObj.appid || paramsObj.type || paramsObj.m);

    return result;
}



/**
 * 验证是否登录
 */
function isLogin(existFunc, noFunc) {
    var user = saveJsonData().getData('user', 1);

    if (user) {
        var data = {
            token: user.token
        };
        var url = createServerUrl('isLogin');

        Common.AjaxGetData(url, data, function (r) {
            if (r.code == 0) {

                var result = r.msg;

                var obj = {
                    id: result.id,
                    name: result.name,
                    token: user.token
                }

                saveJsonData().setData('user', obj, 1);

                existFunc && existFunc();
            } else {
                noFunc && noFunc();
            }
        });
    } else {
        noFunc && noFunc();
    }
}

/**
 * 保存数据的处理方法
 * author:陈偲
 * time:20170811
 * 
 * @param {any} $obj 
 */
function inputDataSaveHandler(identity, type, val, o) {
    if (!o.inputData) {
        o.inputData = {};
    }

    if (!o.inputData[identity]) {
        o.inputData[identity] = {};
    }

    o.inputData[identity].value = val;
    o.inputData[identity].type = type;

    saveJsonData().setData(o.dataName, o.inputData, 1);
}

/**
 * 保存数据的事件
 * author:陈偲
 * time:20170811
 * 
 */
function inputDataSaveEvent(o) {
    if (!o.inputData) {
        o.inputData = {};
    }

    $('input,select').each(function () {
        $(this).on('blur', function () {
            var $this = $(this);
            var type = $this.attr('type');

            if (type === 'text' || type === 'number' || type === 'tel' || type === 'password') {
                inputDataSaveHandler($this.attr('name'), type, $this.val(), o);
            } else if (type === 'checkbox') {
                inputDataSaveHandler('#' + $this.attr('id'), type, $this.get(0).checked, o);
            } else if (type === 'hidden') {
                inputDataSaveHandler('#' + $this.attr('id'), type, $this.val(), o);
            } else if ($this[0].tagName === 'SELECT') {
                inputDataSaveHandler('#' + $this.attr('id'), 'select', $this.val(), o);
            }
        });
    });
}

/*
 * 意见弹出框的处理
 * author:陈偲
 * time:20170807
 */
function confirmProgramBySuggest(options, cancelFunc, certainFunc) {
    var user = saveJsonData().getData('user', 1);

    var $dialog = $('#dialog_suggest');
    var $obj = $("#dialog_suggest,.shadow");
    var $dialogObj = $obj.filter('#dialog_suggest');

    var defaults = $.extend({
        id: null, //主播id
        nick: null, //主播昵称
        innerData: null //需传到服务器的数据
    }, options);

    var settings = $.extend({}, defaults, options);

    /**
     * 把html加入到页面中
     */
    var html = template('templateDialogSuggest', settings);
    // debugger;
    $dialog.html(html);

    var $txt = $('#txt').text('');
    /***************************************** */

    var innerTextArr = [];
    // debugger;
    //平均开播间隔
    innerTextArr.push({
        t1: '平均开播间隔：' + (settings.innerData[0].d1 ? (settings.innerData[0].d1 / 100) : '--') + '天，'
    });
    // innerTextArr.push({
    //     t1: '平均开播间隔：' + (settings.innerData[0].d1 ? (settings.innerData[0].d1 / 100) : '--') + '天，战胜了' + settings.innerData[0].d2 + '%的艺人'
    // });

    //平均开播时长
    innerTextArr.push({
        t1: '平均开播时长：' + settings.innerData[1].d1 / 100 + 'h/天，'
    });
    // innerTextArr.push({
    //     t1: '平均开播时长：' + settings.innerData[1].d1 / 100 + 'h/天，战胜了' + settings.innerData[1].d2 + '%的艺人'
    // });

    //收益时长比
    innerTextArr.push({
        t1: '收益时长比：' + settings.innerData[2].d1 / 100 + '元/h，'
    });
    // innerTextArr.push({
    //     t1: '收益时长比：' + settings.innerData[2].d1 / 100 + '元/h，战胜了' + settings.innerData[2].d2 + '%的艺人'
    // });

    $obj.fadeIn(200);

    /**
     * 输入参数说明
        名称 	类型 	说明 	取值范围 	必选
        token 	string 	用户token 	- 	是
        type 	int 	0.开播间隔 1.开播时长 2.收益时长比 	0-2 	是
        level 	int 	0-2分别代表从低到高的三个区间 	0-2 	是
     */
    var url = createServerUrl('msgTemplate', 'zhoufeng');

    /**
     * 设置上传数据
     */
    var dataArr = [];

    for (var i = 0; i < settings.innerData.length; i++) {
        var item = settings.innerData[i];

        dataArr.push({
            token: user.token,
            type: i
        });

        if (item.d2 < 60) {
            dataArr[i].level = 0;
        } else if (item.d2 < 85) {
            dataArr[i].level = 2;
        } else {
            dataArr[i].level = 1;
        }
    }

    dataArr.forEach(function (item, i) {
        var data = item;

        Common.AjaxGetData(url, data, function (r) {
            /**
                示例:
                {
                    "code":0,
                    "err":"OK",
                    "msg":"建议的模板内容"
                }
                }
            */
            // debugger;
            if (getResult(r.code)) {
                var result = r.msg;

                innerTextArr[i].t2 = result;

                /**
                 * 给文本框添加内容
                 */
                var txtArr = [];

                var txt = $txt.text();

                if (txt) {
                    txtArr.push(txt);
                }
                // debugger;
                txtArr.push(innerTextArr[i].t1 + '\n' + innerTextArr[i].t2);

                $txt.text(txtArr.join('\n\n'));
            } else {
                Common.toast(r.err, 3000);
            }
        });
    });

    $dialogObj.find('.opreate-btn').children().eq(0).one('click', function () {
        cancelFunc && cancelFunc();

        $obj.fadeOut(200, function () {
            $dialog.html('');
        });
    });
    // debugger;
    /**
     * 向艺人提建议
     */
    $dialogObj.find('.opreate-btn').children().eq(1).one('click', function () {
        certainFunc && certainFunc();
        // debugger;
        var result = Common.verificationControlVal([
            '#txt'
        ]);

        if (result) {
            return false;
        }

        /**
         * 输入参数说明
            名称 	类型 	说明 	取值范围 	必选
            token 	string 	用户token 	- 	是
            userId 	string 	目标用户Id 	- 	是
            text 	string 	提建议的内容 	- 	是
         */
        var data = {
            token: user.token,
            userId: settings.id,
            text: $txt.val()
        };

        var url = createServerUrl('advise', 'zhoufeng');

        Common.preloader.show();
        Common.AjaxPostData(url, data, function (r) {
            if (getResult(r.code)) {
                /**
                 * 设置用户信息
                 */
                // o.user.nick = $('#value').val().Trim();
                // saveJsonData().setData('user', o.user, 1);


                $obj.fadeOut(200, function () {
                    $dialog.html('');
                });
            } else {
                Common.toast(r.err, 2345);
            }
        }, null, function () {
            Common.preloader.hide();
        });
    });
}

/*
 * 提醒开播弹出框的处理
 * author:陈偲
 * time:20170807
 */
function confirmProgramByFang(options, cancelFunc, certainFunc) {
    var user = saveJsonData().getData('user', 1);

    var $dialog = $('#dialog_fang');
    var $obj = $("#dialog_fang,.shadow");
    var $dialogObj = $obj.filter('#dialog_fang');

    var defaults = $.extend({
        id: null, //主播id
        nick: null, //主播昵称
    }, options);

    var settings = $.extend({}, defaults, options);

    /**
     * 把html加入到页面中
     */
    var html = template('templateDialogFang', settings);
    // debugger;
    $dialog.html(html);

    var $txt = $('#txt').text('');

    $txt.text('快快开播，一起赚钱！');
    /***************************************** */

    $obj.fadeIn(200);

    $dialogObj.find('.opreate-btn').children().eq(0).one('click', function () {
        cancelFunc && cancelFunc();

        $obj.fadeOut(200, function () {
            $dialog.children().remove();
        });
    });
    // debugger;
    /**
     * 向艺人提建议
     */
    $dialogObj.find('.opreate-btn').children().eq(1).one('click', function () {
        certainFunc && certainFunc();
        // debugger;
        var result = Common.verificationControlVal([
            '#txt'
        ]);

        if (result) {
            return false;
        }

        /**
         * 输入参数说明
            名称 	类型 	说明 	取值范围 	必选
            token 	string 	用户token 	- 	是
            userId 	string 	目标用户Id 	- 	是
            text 	string 	提建议的内容 	- 	是
         */
        var data = {
            token: user.token,
            userId: settings.id,
            text: $txt.val()
        };

        var url = createServerUrl('remind', 'zhoufeng');

        Common.preloader.show();
        Common.AjaxPostData(url, data, function (r) {
            if (getResult(r.code)) {
                /**
                 * 设置用户信息
                 */
                // o.user.nick = $('#value').val().Trim();
                // saveJsonData().setData('user', o.user, 1);


                $obj.fadeOut(200, function () {
                    $dialog.children().remove();
                });
            } else {
                Common.toast(r.err, 2345);
            }
        }, null, function () {
            Common.preloader.hide();
        });
    });
}

/*
 * 是否开播弹出框的处理
 * author:陈偲
 * time:20170808
 */
function confirmProgramByBank(options, cancelFunc, certainFunc) {
    var $dialog = $('#dialog_bank');
    var $obj = $("#dialog_bank,.shadow");
    var $dialogObj = $obj.filter('#dialog_bank');

    $obj.fadeIn(200);

    $dialogObj.find('.opreate-btn').children().eq(0).one('click', function () {
        cancelFunc && cancelFunc();

        $obj.fadeOut(200).unbind();
    });
    // debugger;
    /**
     * 提醒填写银行卡
     */
    $dialogObj.find('.opreate-btn').children().eq(1).one('click', function () {
        certainFunc && certainFunc();

        $obj.fadeOut(200).unbind();
    });
}

/*
 * 弹出审核未通过的提示
 * author:陈偲
 * time:20170810
 */
function alertByNotPass(options, cancelFunc, certainFunc) {
    var user = saveJsonData().getData('user', 1);

    var $dialog = $('#dialog_not_pass');
    var $obj = $("#dialog_not_pass,.shadow");
    var $dialogObj = $obj.filter('#dialog_not_pass');

    /**
     * 把html加入到页面中
     */
    var html = template('templateAlertNotPass', user);
    // debugger;
    $dialog.html(html);

    $obj.fadeIn(200);

    $dialogObj.find('.opreate-btn').children().eq(0).one('click', function () {
        cancelFunc && cancelFunc();

        $obj.fadeOut(200, function () {
            window.location = 'input1.html';
        }).unbind();
    });
}

/*
 * 不能分享的提示
 * author:陈偲
 * time:20170810
 */
function alertByNoShare(options, cancelFunc, certainFunc) {
    var $id = '#alert_no_share';
    var $dialog = $($id);
    var $obj = $($id + ",.shadow");
    var $dialogObj = $obj.filter($id);

    $obj.fadeIn(200);

    $dialogObj.find('.opreate-btn').children().eq(0).one('click', function () {
        cancelFunc && cancelFunc();

        $obj.fadeOut(200).unbind();
    });
}

/*
 * 显示结算规则
 * author:陈偲
 * time:20170814
 */
function alertByPlatformRule(options, cancelFunc, certainFunc) {
    var $id = '#alert_platform_rule';
    var $dialog = $($id);
    var $obj = $($id + ",.shadow");
    var $dialogObj = $obj.filter($id);

    var name = saveJsonData().getData('user', 1).platform;

    var url = createServerUrl('getPlatformInfo', 'zhoufeng');
    // var url = 'test/getPlatformInfo.json';
    var data = {
        platform: name
    };

    Common.preloader.show();
    Common.AjaxGetData(url, data, function (r) {
        /**
            名称 	类型 	说明 	取值范围 	必选
            code 	int 	0. 表示验证码校验通过;1. 身份验证失败;2.数据库相关错误 	0~2 	是
            err 	string 	执行成功可以无视该字段，执行失败返回错误原因 	- 	否
            示例:
            {
                "code":0,
                "err":"OK",
                "msg":
                {
                    "image":"平台图标",
                    "divide":"直播收益(分成比例，单位为万分之一)",
                    "payType":"结算方式",
                    "rule":"审核规则"
                }
            }
         */
        // debugger;
        if (getResult(r.code)) {
            var result = r.msg;

            result.desc1 = result.desc1.replace(/\r\n/g, '<br>');
            result.desc2 = result.desc2.replace(/\r\n/g, '<br>');
            result.desc3 = result.desc3.replace(/\r\n/g, '<br>');

            result.platform = name;

            var html = template('templatePlatformInfo', result);

            $dialog.html(html);

            $obj.fadeIn(200);
        } else {
            Common.toast(r.err, 3000);
        }
    }, null, function () {
        Common.preloader.hide();
    });

    $obj.one('click', function () {
        cancelFunc && cancelFunc();

        $obj.fadeOut(200).unbind();
    });
}

/*
 * 显示微信二维码
 * author:陈偲
 * time:20170815
 */
function alertByWeixinCode(options, cancelFunc, certainFunc) {
    var $id = '#alert_weixin_code';
    var $dialog = $($id);
    var $obj = $($id + ",.shadow");
    var $dialogObj = $obj.filter($id);

    $obj.fadeIn(200);

    $obj.one('click', function () {
        cancelFunc && cancelFunc();

        $obj.fadeOut(200).unbind();
    });
}

/*
 * 拒绝签约的提醒
 * author:陈偲
 * time:20180122
 */
function alertByDisagress(cancelFunc, confirmFunc, data) {
    var $id = '#alert_disagress';
    var $dialog = $($id);
    var $obj = $($id + ",.shadow");
    var $dialogObj = $obj.filter($id);

    $('#alert_disagress_num').text(data);

    $obj.fadeIn(200);

    $dialogObj.find('.opreate-btn').children().eq(0).one('click', function () {
        cancelFunc && cancelFunc();

        $obj.fadeOut(200, function () {
            $('#alert_disagress_num').text('');
        }).unbind();
    });

    $dialogObj.find('.opreate-btn').children().eq(1).one('click', function () {
        confirmFunc && confirmFunc();

        $obj.fadeOut(200, function () {
            $('#alert_disagress_num').text('');
        }).unbind();
    });
}

/**
 * 获取用户信息并保存为永久的user
 * author:陈偲
 * time:20170808
 * @param {*} func 
 */
function getUserInfo(func) {
    var user = saveJsonData().getData('user', 1);
    var url = createServerUrl('getUserInfo', 'zhoufeng');
    var data = {
        token: user.token
    };
    // debugger;
    Common.AjaxPostData(url, data, function (r) {
        /**
            名称 	类型 	说明 	取值范围 	必选
            code 	int 	0. 表示验证码校验通过;1. 身份校验失败;2.数据库连接失败;3.查询用户资料出错 	0~3 	是
            err 	string 	执行成功可以无视该字段，执行失败返回错误原因 	- 	否
            sex 	int 	性别：值为1时是男性，值为2时是女性，值为0时是未知 	0~2 	是
            示例:
            {
                "code":0,
                "err":"OK",
                "msg":
                {
                    "userId":1245678,
                    "state":0,
                    "reason":"审核失败原因",
                    "nick":"用户昵称",
                    "img":"用户头像地址",
                    "platform":"用户所在平台",
                    "time":"成为艺人的日期 2017-08-08",
                    "realName":"真实姓名",
                    "sex":1,
                    "age":22,
                    "mobile":"15801020304",
                    "bankNo":"银行卡号",
                    "bankDetail":"开户行信息",
                    "idInPlatform":"在平台的用户Id"
                }
            }
         */
        if (getResult(r.code)) {
            var result = r.msg;
            var userInfo = result;

            user = $.extend(true, user, userInfo);
            user.nickName = user.nick;

            saveJsonData().setData('user', user, 1);

            if (user.state === 1 &&
                !user.bankNo &&
                user.mobile) {
                confirmProgramByBank(null, null, function () {
                    window.location = 'edit_bank.html';
                });
            }

            if (user.mobile) {
                func && func(user);
            } else {
                window.location = 'index.html#mobile';
            }
        } else {
            Common.toast(r.err, 3000);
        }
    });
}
// function getUserInfo(func) {
//     var user = saveJsonData().getData('user', 1);

//     func && func(user);
// }

var callProtoFunc = {
    callProto: function (url, param) {
        // IOS在safari等设备中iframe无效
        if (navigator.userAgent.match(/\bSafari\/\S+$/) &&
            navigator.userAgent.match(/\b(iPhone|iPad|iPod)\b/)
        ) {
            this.callByLocaiton(url, param);
        } else {
            this.callByIframe(url, param);
        }
    },

    getUrl: function getUrl(url, param) {
        if (param) {
            url = url + (url.match(/\?/) ? '&' : '?') + this.getParam(param);
        }
        return url;
    },

    getParam: function (obj) {
        var str = [];
        for (var k in obj) {
            if (obj.hasOwnProperty(k)) {
                var v = typeof obj[k] !== 'undefined' ? obj[k] : '';
                str.push(encodeURIComponent(k) + '=' + encodeURIComponent(v));
            }
        }
        return str.join('&');
    },

    callByLocaiton: function (url, param) {
        url = this.getUrl(url, param);
        window.location = url;
        console.log(url);
    },

    callByIframe: function (url, param) {
        url = this.getUrl(url, param);
        var iframe = document.createElement('iframe'),
            body = document.getElementsByTagName('body')[0];

        body.appendChild(iframe);

        var style = {
            position: 'fixed',
            zIndex: -1,
            left: 0,
            right: 0,
            width: 0,
            height: 0,
            margin: 0,
            padding: 0,
            border: 'none',
            opacity: 0,
            visibility: 'hidden'
        };
        for (var k in style) {
            iframe.style[k] = style[k];
        }
        iframe.src = url;

        setTimeout(function () {
            body.removeChild(iframe);
        }, 2000);

        console.log(url);
    }

};

//初始化微信分享
function initWeixinShare(func) {
    var param = {
        url: window.location.href.split('#')[0]
    };
    //从后端请求参数
    Common.AjaxPostData(createServerUrl('share', 'zhoufeng'), param, function (r) {
        if (getResult(r.code)) {
            var result = r.msg;

            wx.config({
                debug: false,
                appId: result.appid,
                timestamp: result.timestamp,
                nonceStr: result.nonceStr,
                signature: result.signature,
                menuItem: 'addContact',
                jsApiList: [
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage'
                ]
            });

            func && func();
        } else {
            Common.toast(r.err, 5000);
        }
    });
}

//微信分享
function weixinShare(data) {
    var tempData = {
        title: '',
        imgUrl: '',
        desc: ''
    };

    data = $.extend(tempData, data);

    var title = data.title, // 分享标题
        imgUrl = data.imgUrl, // 分享图标
        desc = data.desc, // 分享描述
        lineLink = data.url || window.location.href; // 分享链接

    $(function () {
        var param = {
            url: window.location.href.split('#')[0],
            token: data.token
        };
        //从后端请求参数
        Common.AjaxPostData(createServerUrl('share', 'zhoufeng'), param, function (r) {
            if (getResult(r.code)) {
                var result = r.msg;

                wx.config({
                    debug: false,
                    appId: OBJ_BAG.weixin_appid,
                    timestamp: result.timestamp,
                    nonceStr: result.nonceStr,
                    signature: result.signature,
                    menuItem: 'addContact',
                    jsApiList: [
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage'
                    ]
                });
            } else {
                Common.toast(r.err, 5000);
            }
        });
    });
    wx.ready(function () {
        wx.onMenuShareTimeline({
            title: title,
            link: lineLink,
            imgUrl: imgUrl
        });

        wx.onMenuShareAppMessage({
            title: title,
            desc: desc,
            link: lineLink,
            imgUrl: imgUrl
        });
    });

    wx.error(function (res) {
        console.log(res);
    });
}

//分页加载数据
function loadPager(data) {
    var PageInfo = {};

    var $obj;

    var tempObj = {
        url: '',
        inputData: {},
        templateName: '',
        controlId: '#',
        isMemoryElementSite: false, //是否记忆元素的位置

        loadDataFunc: null,
        isPager: true,
        completeFunc: null,
        displayFunc: null,
        lastFunc: null,
        noDataFunc: null,

        isFirst: true,
        start: 0,
        count: 32,
        isStartPaging: true
    };

    var obj = $.extend(true, tempObj, data);

    //初始化分页标识
    function initAuntPageInfo() {
        PageInfo = obj;

        PageInfo.start = obj.start || 0;

        $('.nullbox').remove();

        return PageInfo;
    }

    //绑数据
    function bindingListinputData(url, $controlObj, inputData, templateName, func, loadDataFunc, isPager, completeFunc, lastFunc, noDataFunc, displayFunc) {
        inputData.start = PageInfo.start;
        inputData.count = PageInfo.count;
        inputData._time = new Date().getTime();

        Common.AjaxGetData(url, inputData, function (r) {
            if (r || r.msg || !r.code) {
                var result = r.msg;
                var convertResult = null;

                if (loadDataFunc) {
                    convertResult = loadDataFunc(result);
                } else {
                    convertResult = result;
                }

                if (convertResult && convertResult.length) {
                    var html = template('template' + templateName, {
                        'list': convertResult
                    });

                    displayFunc ?
                        (displayFunc &&
                            (function () {
                                displayFunc(html, function () {
                                    loadPagingEvent();

                                    PageInfo.start = $controlObj.find('ul').eq(0).children('.table-row').length;

                                    PageInfo.isStartPaging = true;
                                });
                            })()) :
                        (func && func(html));

                    PageInfo.start = $controlObj.find('ul').eq(0).children('.table-row').length;

                    PageInfo.isStartPaging = true;
                } else {
                    $(window).off("scroll", paging);
                    // $obj.parent().off("scroll", paging);

                    if (inputData.start === 0) {
                        if (noDataFunc) {
                            noDataFunc();
                        } else {
                            $controlObj.append(template('templateNoData', {})).show().find('.nullbox').siblings().hide();
                        }
                    }
                }

                completeFunc && completeFunc(result);
            } else {
                if (loadDataFunc) {
                    loadDataFunc();
                }

                $load_ly_noaunty.show();
            }
        }, function () { }, function () {
            lastFunc && lastFunc();

            PageInfo.isFirst = false;
        });
    }

    //加载分页
    //author:陈偲
    //time:20140701
    function loadPagingEvent(id, pagerControlId) {
        // var obj;

        // if (pagerControlId) {
        //     obj = $(pagerControlId);
        // } else {
        //     obj = $(id).parent();
        // }

        // obj = $(id).find('ul').eq(0);
        // console.log(obj);
        $(window).on("scroll", paging);
    }

    //显示数据
    function displayListinputData(url, inputData, controlId, templateName, loadDataFunc, isPager, pagerControlId, completeFunc, lastFunc, noDataFunc, displayFunc) {
        //inputData = addServerKey(inputData);
        var $controlObj = $(controlId);

        if (PageInfo.isFirst) {

            // $controlObj.find('ul').eq(0).html('');

            bindingListinputData(url, $controlObj, inputData, templateName, function (html) {
                // $controlObj.find('ul').eq(0).html(html);
                $controlObj.find('ul').eq(0).append(html);
                $controlObj.show().find('.nullbox').remove();
                $controlObj.children().show();

                if (isPager) {
                    loadPagingEvent(controlId, pagerControlId);
                }

                // 在这里改!!!
                // myScroll.scrollToElement(document.querySelector('#scroller li:nth-child(10)'))
                // myScroll.scrollTo(0, -100, 1000, IScroll.utils.ease.elastic);

            }, loadDataFunc, isPager, completeFunc, lastFunc, noDataFunc, displayFunc);
        } else {
            bindingListinputData(url, $controlObj, inputData, templateName, function (html) {
                $controlObj.find('ul').eq(0).append(html);
                loadPagingEvent(controlId, pagerControlId);
            }, loadDataFunc, isPager, completeFunc, lastFunc, null, displayFunc);
        }
    }

    //分页判断是否下载下一页
    //author:陈偲
    //time:20140627
    function paging() {
        $obj = $(this);
        var $controlObj = $(obj.controlId).find('ul:visible').eq(0);

        if (PageInfo.isStartPaging) {
            PageInfo.isStartPaging = false;
            var dValue = 70;
            var currentTop = $obj.scrollTop() + $obj.height();
            var scrollHeight = $controlObj.outerHeight(true) + $controlObj.offset().top;
            var showPaging = scrollHeight - dValue;

            if (currentTop > showPaging) {
                PageInfo.pageIndex += 1;
                displayListinputData(obj.url, obj.inputData, obj.controlId, obj.templateName, obj.loadDataFunc, obj.isPager, obj.pagerControlId, obj.completeFunc, null, null, obj.displayFunc);
            } else {
                PageInfo.isStartPaging = true;
            }
        }
    }
    //*************************************************************
    //*************************************************************
    //*************************************************************

    $(window).off("scroll");
    PageInfo = initAuntPageInfo();
    displayListinputData(obj.url, obj.inputData, obj.controlId, obj.templateName, obj.loadDataFunc, obj.isPager, obj.pagerControlId, obj.completeFunc, function () { }, obj.noDataFunc, obj.displayFunc);
}